<template>
  <div class="app-container" :class="{'mobile-container': isMobile}">
    <!-- 移动端骨架屏 -->
    <mobile-skeleton 
      v-if="isMobile && loading" 
      :showHeader="true"
      :showForm="true"
      :formFields="4"
      :showButton="true"
      :showPagination="false"
    />
    
    <div v-else>
      <!-- 桌面端头部 -->
      <el-row :gutter="10" class="test_header" type="flex" align="middle" justify="start" v-if="!isMobile">
        <el-col :span="1">
          <img :src="backImg" style="width: 25px; height: 25px; cursor: pointer; margin-left: 10px" @click="handleBack" />
        </el-col>
        <el-col :span="23">
          <h3 :style="{ color: theme }">考试配置</h3>
        </el-col>
      </el-row>

      <!-- 移动端头部 -->
      <div class="mobile-header" v-if="isMobile">
        <div class="back-btn" @click="handleBack">
          <img :src="backImg" />
        </div>
        <div class="page-title">考试配置</div>
        <div class="placeholder"></div>
      </div>

      <el-form ref="postForm" :model="postForm" :rules="rules" 
        :label-position="isMobile ? 'top' : 'left'" 
        :label-width="isMobile ? '0px' : '120px'"
        :class="{'mobile-form': isMobile}">
        <el-card :class="{'mobile-card': isMobile}">
          <el-form-item label="考试名称" prop="name">
            <el-input v-model="postForm.name" :class="{'mobile-input': isMobile}" />
          </el-form-item>
          
          <el-form-item label="题库分类" prop="name">
            <el-select v-model="postForm.course" filterable clearable placeholder="请选择关联课程" 
              :class="{'mobile-select': isMobile}"
              style="width:100%" @change="repoChange()">
              <el-option :label="item.label" :value="item.id" v-for="item in courseOptions" :key="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="考试开放期限" :required="true">
            <div :class="{'mobile-date-range': isMobile}">
              <el-form-item prop="start_time" :class="{'mobile-date-item': isMobile}">
                <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="postForm.start_time" type="datetime"
                  placeholder="开始时间" :class="{'mobile-date-picker': isMobile}">
                </el-date-picker>
              </el-form-item>
              <span :class="{'mobile-date-separator': isMobile}">至</span>
              <el-form-item prop="end_time" :class="{'mobile-date-item': isMobile}">
                <el-date-picker v-model="postForm.end_time" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"
                  placeholder="结束时间" :class="{'mobile-date-picker': isMobile}">
                </el-date-picker>
              </el-form-item>
            </div>
          </el-form-item>

          <el-form-item label="考试类型" prop="type">
            <el-select v-model="postForm.type" placeholder="请选择考试类型" :class="{'mobile-select': isMobile}">
              <el-option v-for="item in types" :key="item.id" :label="item.label" :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="总分数" prop="totalScore">
            <el-input-number :value="postForm.totalScore" disabled :class="{'mobile-input-number': isMobile}" />
          </el-form-item>

          <el-form-item label="及格分" prop="qualify_score">
            <el-input-number v-model="postForm.qualify_score" :max="postForm.totalScore" :class="{'mobile-input-number': isMobile}" />
          </el-form-item>

          <el-form-item label="考试时长(分钟)" prop="time_limit">
            <el-input-number v-model="postForm.time_limit" :class="{'mobile-input-number': isMobile}" />
          </el-form-item>

          <el-form-item label="改变答案" prop="is_modify">
            <el-checkbox-group v-model="postForm.is_modify" :class="{'mobile-checkbox-group': isMobile}">
              <el-checkbox label="允许考生返回修改答案"></el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item label="提交答案" prop="results">
            <el-checkbox-group v-model="results" disabled :class="{'mobile-checkbox-group': isMobile}">
              <el-checkbox label="显示成绩"></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-card>

        <h3 :style="{ color: theme }" :class="{'mobile-section-title': isMobile}">组卷信息</h3>
        <el-card :class="{'mobile-card': isMobile}">
          <div :class="{'mobile-total-score': isMobile}">
            试卷总分：{{ postForm.totalScore }}分
          </div>
          
          <!-- 移动端卡片式布局 -->
          <div v-if="isMobile" class="mobile-question-cards">
            <div class="mobile-question-card">
              <div class="card-title">单选题</div>
              <div class="card-content">
                <el-form-item prop="single_count" label-width="0">
                  <el-input-number 
                    v-model="postForm.single_count" 
                    :min="0" 
                    :max="postForm.totalText" 
                    :controls="false"
                    class="mobile-input-number"
                    @change="" 
                  />
                </el-form-item>
                <div class="card-count">/ {{ count.single_choice_count }}</div>
              </div>
            </div>

            <div class="mobile-question-card">
              <div class="card-title">多选题</div>
              <div class="card-content">
                <el-form-item prop="multiple_count" label-width="0">
                  <el-input-number 
                    v-model="postForm.multiple_count" 
                    :min="0" 
                    :max="postForm.totalText" 
                    :controls="false"
                    class="mobile-input-number"
                    @change="" 
                  />
                </el-form-item>
                <div class="card-count">/ {{ count.multi_choice_count }}</div>
              </div>
            </div>

            <div class="mobile-question-card">
              <div class="card-title">判断题</div>
              <div class="card-content">
                <el-form-item prop="truefalse_count" label-width="0">
                  <el-input-number 
                    v-model="postForm.truefalse_count" 
                    :min="0" 
                    :max="postForm.totalText" 
                    :controls="false"
                    class="mobile-input-number"
                    @change="" 
                  />
                </el-form-item>
                <div class="card-count">/ {{ count.true_false_count }}</div>
              </div>
            </div>

            <div class="mobile-question-card">
              <div class="card-title">问答题</div>
              <div class="card-content">
                <el-form-item prop="text_count" label-width="0">
                  <el-input-number 
                    v-model="postForm.text_count" 
                    :min="0" 
                    :max="postForm.totalText" 
                    :controls="false"
                    class="mobile-input-number"
                    @change="" 
                  />
                </el-form-item>
                <div class="card-count">/ {{ count.text_count }}</div>
              </div>
            </div>

            <div class="mobile-question-card total-card">
              <div class="card-title">题目总数</div>
              <div class="card-content">
                <div class="total-count">{{total}} /{{ count.count }}</div>
              </div>
            </div>
          </div>

          <!-- 桌面端表格布局 -->
          <div v-else>
            <table class="ct_table" v-loading="loading">
              <th class="tb_head">单选题数量</th>
              <th class="tb_head">多选题数量</th>
              <th class="tb_head">判断题数量</th>
              <th class="tb_head">问答题数量</th>
              <th class="tb_head">题目总数</th>

              <tr>
                <td style="text-align: center;">
                  <el-form-item prop="single_count" label-width="0">
                    <el-input-number v-model="postForm.single_count" :min="0" :max="postForm.totalText" :controls="false"
                      style="width: 60%" @change="" />
                    / {{ count.single_choice_count }}
                  </el-form-item>
                </td>
                <td style="text-align: center;">
                  <el-form-item prop="multiple_count" label-width="0">
                    <el-input-number v-model="postForm.multiple_count" :min="0" :max="postForm.totalText" :controls="false"
                      style="width: 60%" @change="" />
                    / {{ count.multi_choice_count }}
                  </el-form-item>
                </td>
                <td style="text-align: center;">
                  <el-form-item prop="truefalse_count" label-width="0">
                    <el-input-number v-model="postForm.truefalse_count" :min="0" :max="postForm.totalText" :controls="false"
                      style="width: 60%" @change="" />
                    / {{ count.true_false_count }}
                  </el-form-item>
                </td>
                <td style="text-align: center;">
                  <el-form-item prop="text_count" label-width="0">
                    <el-input-number v-model="postForm.text_count" :min="0" :max="postForm.totalText" :controls="false"
                      style="width: 60%" @change="" />
                    / {{ count.text_count }}
                  </el-form-item>
                </td>
                <td style="text-align: center;">
                  {{total}} /{{ count.count }}
                </td>
              </tr>
            </table>
          </div>
        </el-card>

        <h3 :style="{ color: theme }" :class="{'mobile-section-title': isMobile}">权限配置</h3>
        <el-card :class="{'mobile-card': isMobile}">
          <el-form-item label="阅卷人">
            <el-select v-model="postForm.manager" placeholder="请选择.." filterable clearable :class="{'mobile-select': isMobile}">
              <el-option :label="manager.name" :value="manager.id" v-for="manager in managerOptions" :key="manager.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="参考人员">
            <div :class="{'mobile-tree': isMobile}">
              <el-tree :data="userOptions" show-checkbox node-key="name" :default-checked-keys="postForm.user"
                :props="defaultProps" ref="tree" :check-on-click-node="true" :required=true>
              </el-tree>
            </div>
          </el-form-item>
        </el-card>
      </el-form>

      <div :class="{'mobile-action-container': isMobile, 'desktop-submit-container': !isMobile}">
        <el-button type="primary" @click="handleSave" :style="{
          backgroundColor: theme,
          borderColor: theme,
          fontWeight: 'bold',
          width: isMobile ? '100%' : 'auto',
          height: isMobile ? '44px' : 'auto',
          fontSize: isMobile ? '16px' : '14px'
        }">提交</el-button>
      </div>
      
      <!-- 移动端底部占位，防止内容被底部菜单遮挡 -->
      <div v-if="isMobile" class="mobile-bottom-placeholder"></div>
    </div>
  </div>
</template>

<script>
import { fetchDetail, saveData } from "@/api/vadmin/exam/exam";
import { fetchTree } from "@/api/sys/depart/depart";
import RepoSelect from "@/components/RepoSelect";
import { listUser } from "@/api/vadmin/permission/user";
import { mapGetters, mapState } from "vuex";
import variables from "@/assets/styles/variables.scss";
import backImg from "@/assets/images/back.png";
import {
  examDetail,
  addExam,
  updateExam,
  questionStatistics,
} from "@/api/vadmin/exam/exam";
import { treeselectDeptUser } from "@/api/vadmin/permission/dept";
import { categoryTree } from "@/api/vadmin/course/course";
import "@/assets/styles/mobile/exam.scss";
import MobileSkeleton from "@/components/MobileSkeleton";
export default {
  name: "ExamDetail",
  components: { 
    RepoSelect,
    MobileSkeleton 
  },
  data() {
    return {
      backImg: backImg,
      defaultProps: {
        children: "users",
        label: "name",
      },
      filterText: "",
      treeLoading: false,
      loading: true,
      dateValues: [],
      // 已选择的题库
      excludes: [],
      //课程分类
      courseOptions: [],
      //考试类型
      types: [
        { id: "1", label: "正常考试" },
        { id: "2", label: "认证考试" },
        { id: "3", label: "培训考试" },
        { id: "4", label: "以考代训" },
      ],
      postForm: {
        // 总分数
        totalScore: 100,
        // 题库列表
        is_modify: true,
        course: "",
        total: '',//题目总数
        manager: '',
        text_count:0,// 问答题数量
        single_count: 0, // 已选单选题数量
        multiple_count: 0, // 已选多选题数量
        truefalse_count: 0, // 已选判断题数量
        user:[]
      },
      //试卷题目数量
      count:{
        multi_choice_count:0,//多
        single_choice_count:0,//单
        text_count:0,//问答
        true_false_count:0,//判断
        count:0//所有
      },
      //显示成绩
      results: true,
      userOptions: [],
      managerOptions: [],
      isMobile: false,
      mediaQueryList: null,
      rules: {
        name: [{ required: true, message: "考试名称不能为空！" }],
        open: [{ required: true, message: "考试权限不能为空！" }],
        course: [{ required: true, message: "课程选择不能为空" }],

        text_count: [{ required: true, message: "问答题不能为空" }],
        multiple_count: [{ required: true, message: "多选题不能为空" }],
        single_count: [{ required: true, message: "单选题不能为空" }],
        truefalse_count: [{ required: true, message: "判断题题不能为空" }],
        totalScore: [{ required: true, message: "考试分数不能为空！" }],

        qualify_score: [{ required: true, message: "及格分不能为空！" }],
        totalTime: [{ required: true, message: "考试时间不能为空！" }],
        time_limit: [{ required: true, message: "考试时长不能为空！" }],
        type: [{ required: true, message: "考试类型不能为空" }],
        user: [{ required: true, message: "参考人员不能为空" }],
      },
    };
  },
  computed: {
    ...mapState(["settings"]),
    variables() {
      return variables;
    },
    theme() {
      return this.$store.state.settings.theme;
    },
    total() {
      // 确保所有值都是数字
      const singleCount = Number(this.postForm.single_count) || 0;
      const multipleCount = Number(this.postForm.multiple_count) || 0;
      const truefalseCount = Number(this.postForm.truefalse_count) || 0;
      const textCount = Number(this.postForm.text_count) || 0;
      
      // 计算总和
      return singleCount + multipleCount + truefalseCount + textCount;
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },

    dateValues: {
      handler() {
        this.postForm.startTime = this.dateValues[0];
        this.postForm.endTime = this.dateValues[1];
      },
    },
   


  },
  created() {
    this.getBasicData();
    this.getCount();
    const id = this.$route.params.id;
    if (typeof id !== "undefined") {
      this.getExamData(id);
    }
  },
  mounted() {
    // 使用媒体查询API直接监听视口变化
    this.mediaQueryList = window.matchMedia('(max-width: 767px)');
    
    // 初始化isMobile状态
    this.isMobile = this.mediaQueryList.matches;
    
    // 为媒体查询添加监听器
    const handleMediaChange = (e) => {
      this.isMobile = e.matches;
      
      // 强制组件重新渲染
      this.$forceUpdate();
    };
    
    // 使用适当的API添加监听器
    if (this.mediaQueryList.addEventListener) {
      this.mediaQueryList.addEventListener('change', handleMediaChange);
    } else {
      // 旧版浏览器支持
      this.mediaQueryList.addListener(handleMediaChange);
    }
    
    // 存储监听器以便后续移除
    this.mediaChangeHandler = handleMediaChange;
  },
  beforeDestroy() {
    // 移除媒体查询监听器
    if (this.mediaQueryList) {
      if (this.mediaQueryList.removeEventListener) {
        this.mediaQueryList.removeEventListener('change', this.mediaChangeHandler);
      } else {
        // 旧版浏览器支持
        this.mediaQueryList.removeListener(this.mediaChangeHandler);
      }
    }
  },
  methods: {
    getBasicData() {
      // 获取阅卷人
      listUser({ page_size: 10000, page: 1 }).then((response) => {
        this.managerOptions = response.results;
      });
      // 获取所有参考人员
      treeselectDeptUser({ page_size: 1000, page: 1 }).then((response) => {
        this.userOptions = this.handleUsersTree(response.results, "id");
      });

      //课程分类
      categoryTree({ page_size: 1000, page: 1 }).then((response) => {
        // console.log(999, response)
        this.courseOptions = response;
      });
      // this.getListKnowledge()
    },
    getExamData(id) {
      examDetail(id).then((res) => {
        // console.log("21212", res);
        this.postForm = res;
        this.postForm.course = res.course.id;
        this.repoChange()
        this.postForm.user = res.user.map((item) => {
          return item.name;
        });
        this.postForm.totalScore = 100;
      });
    },
    // getListKnowledge() {
    //   //所有知识点
    //   getQuestion({ category: this.postForm.course, page: 1, page_size: 1000000000 }).then((response) => {

    //     this.$set(this.postForm, "total", response.count);
    //   });
    // },
    reset() {
      this.postForm = {
        totalScore: 100,
        // 题库列表
        is_modify: true,
        course: "",
      };
    },
    resetChecked() {
      this.$refs.tree.setCheckedKeys([]);
    },
    handleSave() {
      // 获取选中的人员
      this.postForm.user = this.$refs.tree
        .getCheckedNodes()
        .filter((item) => {
          return !item.users;
        })
        .map((item) => {
          return item.id;
        });

      this.$refs.postForm.validate((valid) => {
        if (!valid) {
          return;
        }

        // 验证每种题型的数量不超过题库中的总数
        if (!this.validateQuestionCounts()) {
          return;
        }

        if (this.postForm.totalScore === 0) {
          this.$notify({
            title: "提示信息",
            message: "考试规则设置不正确，请确认！",
            type: "warning",
            duration: 2000,
          });

          return;
        }
        // console.log(2222, this.postForm)
        if (this.postForm.text_count > 0 && this.postForm.manager == '') {
          this.msgError("该试卷已选择问答题，请选择阅卷人");
        } else {
          this.$confirm("确实要提交保存吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            this.submitForm();
          });
        }
      });
    },
    getCount() {
      this.loading = true;
      questionStatistics({ category: this.postForm.course }).then((res) => {
    
        this.count= res
      
        this.loading = false;
      });
    },
    submitForm() {
      this.$refs["postForm"].validate((valid) => {
        // console.log("结果", this.postForm);

        if (valid) {
          if (this.postForm.id != undefined) {
            updateExam(this.postForm)
              .then((response) => {
                this.msgSuccess("修改成功");
              })
              .catch((err) => {
                this.msgError(err.msg);
              });
          } else {
            this.postForm.state = 1; //设置默认开启考试
            console.log(3333,this.postForm)
            addExam(this.postForm)
              .then((res) => {
                // console.log("提交验证信息", res);
                this.reset();
                this.resetChecked();
                this.msgSuccess("新建成功");
              })
              .catch((err) => {
                this.msgError(err.msg);
              });
          }
        }

      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.deptName.indexOf(value) !== -1;
    },

    repoChange() {

      // this.reset()
      // this.getListKnowledge()
      this.getCount();
    },
    reset() {

      this.postForm.text_count = ''
    },
    handleBack() {
      this.$router.back()//返回浏览器上一页，并保留上一页数据
    },
    // 验证题目数量
    validateQuestionCounts() {
      // 检查单选题数量
      if (this.postForm.single_count > this.count.single_choice_count) {
        this.msgError(`单选题数量不能超过题库中的可用数量(${this.count.single_choice_count})`);
        return false;
      }
      
      // 检查多选题数量
      if (this.postForm.multiple_count > this.count.multi_choice_count) {
        this.msgError(`多选题数量不能超过题库中的可用数量(${this.count.multi_choice_count})`);
        return false;
      }
      
      // 检查判断题数量
      if (this.postForm.truefalse_count > this.count.true_false_count) {
        this.msgError(`判断题数量不能超过题库中的可用数量(${this.count.true_false_count})`);
        return false;
      }
      
      // 检查问答题数量
      if (this.postForm.text_count > this.count.text_count) {
        this.msgError(`问答题数量不能超过题库中的可用数量(${this.count.text_count})`);
        return false;
      }
      
      return true;
    },
  },
};
</script>

<style lang="scss" scoped>
.pre-exam div {
  line-height: 42px;
  color: #555555;
}

.post-tree {
  border: 1px solid #dcdfe6;
}

.el-tree {
  z-index: 2;
}

.ct_table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px !important;
  padding: 10px 0;

  tr {
    height: 40px;
  }

  td {}

  .tb_head {
    font-size: 16px;
    font-weight: 400;
    width: 140px;
    padding: 10px 0;
    background: #e4e4e4;
    padding-left: 20px;
  }

  .custom-table-td {
    width: 200px;
    font-size: 16px;
    font-weight: 400;
    color: #333333;
    padding: 10px 20px 10px;
  }

  .w180 {
    width: 180px;
  }
}

// 桌面端样式
.desktop-submit-container {
  margin-top: 20px;
}

// 移动端样式
.mobile-container {
  padding: 0;
  background: #f5f7fa;
}

.mobile-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: #fff;
  border-bottom: 1px solid #eee;
  position: sticky;
  top: 0;
  z-index: 100;

  .back-btn {
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    
    img {
      width: 20px;
      height: 20px;
    }
  }

  .page-title {
    font-size: 18px;
    font-weight: 500;
    color: #333;
  }

  .placeholder {
    width: 24px;
  }
}

.mobile-form {
  .el-form-item {
    margin-bottom: 16px;
  }

  .el-form-item__label {
    padding: 0 0 8px 0;
    font-size: 14px;
    color: #666;
  }
}

.mobile-card {
  margin: 12px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
}

.mobile-input,
.mobile-select,
.mobile-date-picker {
  width: 100% !important;
}

.mobile-date-range {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.mobile-date-item {
  margin-bottom: 8px;
}

.mobile-date-separator {
  text-align: center;
  color: #666;
  margin: 4px 0;
}

.mobile-section-title {
  margin: 16px 12px 8px;
  font-size: 16px;
  font-weight: 500;
}

.mobile-total-score {
  color: #ff0000;
  font-weight: bold;
  margin-bottom: 12px;
  text-align: right;
  padding-right: 12px;
}

.mobile-question-cards {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 8px 0;
}

.mobile-question-card {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 12px;
  
  .card-title {
    font-size: 14px;
    color: #666;
    margin-bottom: 8px;
  }
  
  .card-content {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .el-form-item {
      margin-bottom: 0;
      flex: 1;
    }
    
    .card-count {
      color: #666;
      font-size: 14px;
      min-width: 60px;
      text-align: right;
    }
  }
}

.total-card {
  background: #f0f7ff;
  border: 1px solid #e6f0ff;
  
  .card-title {
    color: #409EFF;
    font-weight: 500;
  }
  
  .total-count {
    font-size: 16px;
    font-weight: 500;
    color: #409EFF;
  }
}

.mobile-input-number {
  width: 100% !important;
  
  .el-input-number__decrease,
  .el-input-number__increase {
    display: none;
  }
  
  .el-input__inner {
    text-align: center;
    height: 36px;
    line-height: 36px;
  }
}

.mobile-tree {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 8px;
}

.mobile-action-container {
  position: fixed;
  bottom: 50px; // 调整位置，避免被底部菜单遮挡
  left: 0;
  right: 0;
  padding: 12px 16px;
  background: #fff;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
  z-index: 100;
}

.mobile-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

// 添加底部占位元素样式
.mobile-bottom-placeholder {
  height: 80px; // 为底部按钮和菜单预留空间
  width: 100%;
}

// 桌面端样式保持不变
.desktop-submit-container {
  margin-top: 20px;
  text-align: center;
}
</style>